//
//  MILSenceSettingViewController.m
//  MicrowaveInteractionLight
//
//  Created by maple on 2017/1/10.
//  Copyright © 2017年 maple. All rights reserved.
//

#import "MILSenceSettingViewController.h"
#import "CircleSliderView.h"
#import "SaveSceneApi.h"

@interface MILSenceSettingViewController ()

/** 圆形灯光调色板 **/
@property(nonatomic,strong) CircleSliderView *circleSliderView;

/** 工作模式 **/
@property(nonatomic,strong) UIButton *senceNameButton;
@property(nonatomic,copy) NSString *senceName;

/** 亮度 **/
@property(nonatomic,strong) UISlider *brightnessSlider;
@property(nonatomic,strong) UILabel *brightnessLabel;

/** 色温 **/
@property(nonatomic,strong) UISlider *colorTemperatureSlider;
@property(nonatomic,strong) UILabel *colorTemperatureLabel;

/** 闪烁频率 **/
@property(nonatomic,strong) UISlider *twinkleSlider;
@property(nonatomic,strong) UILabel *twinkleLabel;

@property(nonatomic,strong) UIColor *lightColor;

@end

@implementation MILSenceSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];

}

- (void)refreshBaseControlValue
{
    [self setNavigationBarTitle:@"场景模式设置"];
    
    [self hideNavigationBottomLine];
    self.view.backgroundColor = [UIColor colorWithRed:52/255.0 green:52/255.0 blue:52/255.0 alpha:1];
    [self setRightButtonTitle:@"保存"];
    [self masLayoutSubviews];
}

#pragma mark -- 事件
- (void)onRightButtonClick:(id)sender {
    if (self.run) {
        [SVProgressHUD showErrorWithStatus:@"场景运行中不能修改，保存失败"];
        return;
    }
    
    if (self.senceName == nil) {
        [SVProgressHUD showErrorWithStatus:@"请输入模式名称"];
        return;
    }
    
    if (self.senceModel.r == nil || self.senceModel.r == nil || self.senceModel.r == nil) {
        [SVProgressHUD showErrorWithStatus:@"请选择颜色"];
        return;
    }
    
    if (self.senceModel.brightness == nil) {
        [SVProgressHUD showErrorWithStatus:@"请选择亮度"];
        return;
    }
    
    if (self.senceModel.colour_temperature == nil) {
        [SVProgressHUD showErrorWithStatus:@"请选择色温"];
        return;
    }
    
    if (self.senceModel.twinkle == nil) {
        [SVProgressHUD showErrorWithStatus:@"请选择闪烁频率"];
        return;
    }
    
    
    CGFloat red;
    CGFloat green;
    CGFloat blue;
    CGFloat alpha;
    CGFloat hue;
    CGFloat saturation;
    CGFloat brightness;
    [self.lightColor getRed:&red green:&green blue:&blue alpha:&alpha];
    
    // 转换成HSB添加亮度和色温
    [self.lightColor getHue:&hue saturation:&saturation brightness:&brightness alpha:&alpha];
    brightness = (CGFloat)[self.senceModel.brightness intValue]/100;
    saturation = (CGFloat)[self.senceModel.colour_temperature intValue]/100;
    UIColor *controlColor = [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:alpha];
    [controlColor getRed:&red green:&green blue:&blue alpha:&alpha];
    // 颜色取反
    red = 1 - red;
    green = 1 - green;
    blue = 1 - blue;
    NSArray *colorArray = [UIColor changeUIColorToRGB:[UIColor colorWithRed:red green:green blue:blue alpha:1]];
    if (colorArray.count == 3) {
        SaveSceneApi *api = [[SaveSceneApi alloc] initWithDictionary:@{@"id":[NSString stringWithFormat:@"%ld",(long)self.senceID],
                                                                       @"name":self.senceName,
                                                                       @"device_id":self.deviceID,
                                                                       @"r":colorArray[0],
                                                                       @"g":colorArray[1],
                                                                       @"b":colorArray[2],
                                                                       @"brightness":self.senceModel.brightness,
                                                                       @"colour_temperature":self.senceModel.colour_temperature,
                                                                       @"twinkle":self.senceModel.twinkle}];
        [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
            NSDictionary *dic = request.responseJSONObject;
            if ([dic[@"errcode"] intValue] == 0) {
                [SVProgressHUD showSuccessWithStatus:dic[@"errmsg"]];
                [self.navigationController popViewControllerAnimated:YES];
            } else {
                [SVProgressHUD showErrorWithStatus:dic[@"errmsg"]];
            }
        } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
            [SVProgressHUD showErrorWithStatus:request.responseJSONObject[@"errmsg"]];
        }];
    }

    
}

- (void)onBrightnessThumb:(UISlider *)sender{
    NSString *brightness = [NSString stringWithFormat:@"%i%%",(int)sender.value];
    self.brightnessLabel.text = brightness;
    self.senceModel.brightness = [NSString stringWithFormat:@"%i",(int)sender.value];
    
}
- (void)endBrightnessThumb:(UISlider *)sender{
    
}

- (void)onColorTemperatureThumb:(UISlider *)sender{
    NSString *colorTemperature = [NSString stringWithFormat:@"%i%%",(int)sender.value];
    self.colorTemperatureLabel.text = colorTemperature;
    self.senceModel.colour_temperature = [NSString stringWithFormat:@"%i",(int)sender.value];

}
- (void)endColorTemperatureThumb:(UISlider *)sender{
    
}

- (void)onTwinkleThumb:(UISlider *)sender{
    NSString *twinkle = [self getTwinkleWithSliderValue:sender.value];
    self.twinkleLabel.text = twinkle;
    self.senceModel.twinkle = [NSString stringWithFormat:@"%i",(int)sender.value];
    
}
- (void)endTwinkleThumb:(UISlider *)sender{
    
}

- (NSString *)getTwinkleWithSliderValue:(NSInteger)value {
    NSString *string = [[NSString alloc] init];
    
    switch (value) {
            break;
        case 0:
            string = @"0";
            break;
        case 1:
            string = @"0.1s";
            break;
        case 2:
            string = @"0.25s";
            break;
        case 3:
            string = @"0.5s";
            break;
        case 4:
            string = @"1s";
            break;
        case 5:
            string = @"2s";
            break;
        default:
            break;
    }
    return string;
}

- (void)didClickLightNameButton{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"请输入灯泡名称" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    UITextField *nickFeild = [alert textFieldAtIndex:0];
    nickFeild.font = [UIFont systemFontOfSize:11];
    nickFeild.placeholder = @"请在此处输入灯泡名称";
    alert.tag = 200;
    [alert show];
}


#pragma mark  alertView修改昵称事件
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if (buttonIndex == 1)
    {
        switch (alertView.tag)
        {
            case 200:
            {
                //此处向服务器提交修改昵称的请求
                
                UITextField *nickTextField = [alertView textFieldAtIndex:0];
                [nickTextField endEditing:YES];
                if (nickTextField.text.length>10) {
                    [SVProgressHUD showErrorWithStatus:@"名字长度不能超过10个"];
                    return;
                }
                
                if ([NSString isContainsTwoEmoji:nickTextField.text ]) {
                    [SVProgressHUD showErrorWithStatus:@"名字不能使用表情"];
                    return;
                }
                
                [self.senceNameButton setTitle:nickTextField.text forState:UIControlStateNormal];
                [self.senceNameButton setImage:[UIImage imageNamed:@"bianji"] forState:UIControlStateNormal];
                [self.senceNameButton layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleRight imageTitleSpace:5];
                self.senceName = nickTextField.text;
                
            }
                break;
            default:
                break;
        }
        
    }
    
}



- (void)masLayoutSubviews{
    
    __weak UIView *superView = self.view;
    
    
    [self.senceNameButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(superView).with.offset(64+px1920Height(80));
        make.height.mas_equalTo(px1920Height(60));
        make.width.mas_equalTo(superView);
    }];
    
    UIView *line = [[UIView alloc] init];
    line.backgroundColor = [UIColor darkGrayColor];
    [superView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.senceNameButton.mas_bottom).with.offset(px1920Height(40));
        make.left.mas_equalTo(superView).with.offset(px1080Width(30));
        make.right.mas_equalTo(superView).with.offset(-px1080Width(30));
        make.height.mas_equalTo(2);
    }];
    
    [self.circleSliderView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(superView);
        make.top.equalTo(self.senceNameButton.mas_bottom).with.offset(px1920Height(80));
        make.height.width.mas_equalTo(px1080Width(675));
    }];
 
    
    int count = 3;
    UIView *lastView = nil;
    NSArray *sliderArray = @[self.brightnessSlider,self.colorTemperatureSlider,self.twinkleSlider];
    NSArray *labelArray = @[self.brightnessLabel,self.colorTemperatureLabel,self.twinkleLabel];
    NSArray *labelTitleArray = @[@"亮度",@"色温",@"闪烁频率"];
    
    for(int i = 0;i < count;++i ){
        //创建一个View
        
        UILabel *title = [[UILabel alloc] init];
        title.font = [UIFont systemFontOfSize:15];
        title.textColor = [UIColor whiteColor];
        title.text = labelTitleArray[i];
        [superView addSubview:title];
        
        CGFloat titleWidth;
        if (i == 2) {
            titleWidth = px1080Width(240);
        } else {
            titleWidth = px1080Width(120);
        }
        
        //向subView添加约束
        [title mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(titleWidth);
            make.height.mas_equalTo(px1080Width(40));
            make.left.equalTo(self.view).with.offset(px1080Width(90));
            
            //判断是否有前一个子View
            if ( lastView ) {
                //如果有前一个View，上边界和前一个View的下边界紧贴
                make.top.mas_equalTo(lastView.mas_bottom).with.offset(px1920Height(140));
            } else {
                //如果没有前一个View，上边界和container的下边界紧贴
                make.top.mas_equalTo(self.circleSliderView.mas_bottom).with.offset(px1920Height(120));
            }
        }];
        
        [superView addSubview:labelArray[i]];
        [labelArray[i] mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo(title.mas_centerY);
            make.width.mas_equalTo(px1080Width(150));
            make.height.mas_equalTo(px1080Width(40));
            make.right.equalTo(self.view).with.offset(-px1080Width(90));
        }];
        
        [superView addSubview:sliderArray[i]];
        [sliderArray[i] mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo(title.mas_centerY);
            make.left.mas_equalTo(title.mas_right).with.offset(px1080Width(35));
            make.right.mas_equalTo(superView).with.offset(-px1080Width(250));
            make.height.mas_equalTo(px1080Width(80));
        }];
        
        //保存前一个View
        lastView = title;
    }
    
}


// 将16进制颜色转换成UIColor，再取反，获得颜色、亮度、色温
- (void)getColor:(UIColor *)originalColor result:(void(^)(UIColor *color,CGFloat saturation, CGFloat brightness,CGFloat hue))result{
//    UIColor *originalColor = [UIColor colorWithHexString:[NSString stringWithFormat:@"#%@",hexString]];
    CGFloat hue;
    CGFloat saturation;
    CGFloat brightness;
    CGFloat alpha;
    CGFloat red;
    CGFloat green;
    CGFloat blue;
    // RGB取反
    [originalColor getRed:&red green:&green blue:&blue alpha:&alpha];
    UIColor *negationColor = [UIColor colorWithRed:1-red green:1-green blue:1-blue alpha:1];
    // 取出亮度和色温
    [negationColor getHue:&hue saturation:&saturation brightness:&brightness alpha:&alpha];
    UIColor *color = [UIColor colorWithHue:hue saturation:1 brightness:1 alpha:1];
    [color getRed:&red green:&green blue:&blue alpha:&alpha];
    //    NSLog(@"原始颜色：%f,%f,%f\n转换颜色：%f,%f,%f",red,green,blue,1-red,1-green,1-blue);
    result([UIColor colorWithRed:red green:green blue:blue alpha:alpha],saturation,brightness,hue);
}

#pragma mark -- 懒加载
- (CircleSliderView *)circleSliderView
{
    if(!_circleSliderView)
    {
        __weak UIView *superView = self.view;
        _circleSliderView = [[CircleSliderView alloc]initWithFrame:CGRectMake(self.view.center.x-125, 64, px1080Width(675), px1920Height(675))];
        [superView addSubview:_circleSliderView];
        _circleSliderView.imageName = @"ring";
        UIColor *color = [UIColor colorWithRed:[self.senceModel.r intValue]/255.0 green:[self.senceModel.g intValue]/255.0 blue:[self.senceModel.b intValue]/255.0 alpha:1];
        [self getColor:color result:^(UIColor *color, CGFloat saturation, CGFloat brightness, CGFloat hue) {
            _circleSliderView.imageColor = color;
        }];

        __weak typeof(self) weakSelf = self;
        _circleSliderView.returnColorBlock = ^(UIColor *color) {
            weakSelf.lightColor = color;
            NSLog(@"circleColor:%@",[UIColor changeUIColorToRGB:color]);
            NSArray *colorArray = [UIColor changeUIColorToRGB:color];
            if (colorArray.count == 3) {
                weakSelf.senceModel.r = colorArray[0];
                weakSelf.senceModel.g = colorArray[1];
                weakSelf.senceModel.b = colorArray[2];
            }
        };
    }
    return _circleSliderView;
}



- (UIButton *)senceNameButton
{
    if(!_senceNameButton)
    {
        UIView *superView = self.view;
        _senceNameButton = [[UIButton alloc]init];
        [superView addSubview:_senceNameButton];

        [_senceNameButton addTarget:self action:@selector(didClickLightNameButton) forControlEvents:UIControlEventTouchUpInside];
//        _senceNameButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        NSString *name = [[NSString alloc] init];
        if (self.senceID == 0) {
            name = @"请输入模式名称";
        } else {
            name = self.senceModel.name;
            self.senceName = self.senceModel.name;
        }
        [_senceNameButton setTitle:name forState:UIControlStateNormal];
        [_senceNameButton setImage:[UIImage imageNamed:@"bianji"] forState:UIControlStateNormal];
        [_senceNameButton layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleRight imageTitleSpace:15];
    }
    return _senceNameButton;
}

- (UISlider *)brightnessSlider
{
    if(!_brightnessSlider)
    {
//        UIView *superView = self.view;
        _brightnessSlider = [[UISlider alloc]init];
//        [superView addSubview:_variabilitySlider];
        _brightnessSlider.value = [self.senceModel.brightness intValue];
        _brightnessSlider.minimumValue = 0;
        _brightnessSlider.maximumValue = 100;
        [_brightnessSlider setMinimumTrackTintColor:[UIColor whiteColor]];
        [_brightnessSlider setMaximumTrackTintColor:[UIColor darkGrayColor]];
        [_brightnessSlider setThumbImage:[UIImage imageNamed:@"slider"] forState:UIControlStateNormal];
        //滑动过程中不断触发事件
        [_brightnessSlider addTarget:self action:@selector(onBrightnessThumb:) forControlEvents:UIControlEventValueChanged];
        //滑动完成后触发事件
        [_brightnessSlider addTarget:self action:@selector(endBrightnessThumb:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _brightnessSlider;
}



- (UISlider *)colorTemperatureSlider
{
    if(!_colorTemperatureSlider)
    {
//        UIView *superView = self.view;
        _colorTemperatureSlider = [[UISlider alloc]init];
//        [superView addSubview:_colorTemperatureSlider];
        _colorTemperatureSlider.value = [self.senceModel.colour_temperature intValue];
        _colorTemperatureSlider.minimumValue = 0;
        _colorTemperatureSlider.maximumValue = 100;
        [_colorTemperatureSlider setMinimumTrackTintColor:[UIColor whiteColor]];
        [_colorTemperatureSlider setMaximumTrackTintColor:[UIColor darkGrayColor]];
        [_colorTemperatureSlider setThumbImage:[UIImage imageNamed:@"slider"] forState:UIControlStateNormal];
        //滑动过程中不断触发事件
        [_colorTemperatureSlider addTarget:self action:@selector(onColorTemperatureThumb:) forControlEvents:UIControlEventValueChanged];
        //滑动完成后触发事件
        [_colorTemperatureSlider addTarget:self action:@selector(endColorTemperatureThumb:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _colorTemperatureSlider;
}
- (UISlider *)twinkleSlider
{
    if(!_twinkleSlider)
    {
//        UIView *superView = self.view;
        _twinkleSlider = [[UISlider alloc]init];
//        [superView addSubview:_flickerFrequencySlider];
        //        _flickerFrequencySlider.value = 1.0;
        _twinkleSlider.minimumValue = 0;
        _twinkleSlider.maximumValue = 5;
        _twinkleSlider.value = [self.senceModel.twinkle intValue];
        [_twinkleSlider setMinimumTrackTintColor:[UIColor whiteColor]];
        [_twinkleSlider setMaximumTrackTintColor:[UIColor darkGrayColor]];
        [_twinkleSlider setThumbImage:[UIImage imageNamed:@"slider2"] forState:UIControlStateNormal];
        //滑动过程中不断触发事件
        [_twinkleSlider addTarget:self action:@selector(onTwinkleThumb:) forControlEvents:UIControlEventValueChanged];
        //滑动完成后触发事件
        [_twinkleSlider addTarget:self action:@selector(endTwinkleThumb:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _twinkleSlider;
}


- (UILabel *)brightnessLabel
{
    if(!_brightnessLabel)
    {
//        UIView *superView = self.view;
        _brightnessLabel = [[UILabel alloc]init];
//        [superView addSubview:_variabilityLabel];
        [_brightnessLabel setFont:[UIFont systemFontOfSize:15]];
        [_brightnessLabel setTextColor:[UIColor whiteColor]];
        _brightnessLabel.textAlignment = NSTextAlignmentRight;
       
    }
    return _brightnessLabel;
}
- (UILabel *)colorTemperatureLabel
{
    if(!_colorTemperatureLabel)
    {
//        UIView *superView = self.view;
        _colorTemperatureLabel = [[UILabel alloc]init];
//        [superView addSubview:_colorTemperatureLabel];
        [_colorTemperatureLabel setFont:[UIFont systemFontOfSize:15]];
        [_colorTemperatureLabel setTextColor:[UIColor whiteColor]];
        _colorTemperatureLabel.textAlignment = NSTextAlignmentRight;

    }
    return _colorTemperatureLabel;
}
- (UILabel *)twinkleLabel
{
    if(!_twinkleLabel)
    {
//        UIView *superView = self.view;
        _twinkleLabel = [[UILabel alloc]init];
//        [superView addSubview:_flickerFrequencyLabel];
        [_twinkleLabel setFont:[UIFont systemFontOfSize:15]];
        [_twinkleLabel setTextColor:[UIColor whiteColor]];
        _twinkleLabel.textAlignment = NSTextAlignmentRight;

    }
    return _twinkleLabel;
}

- (void)setSenceID:(NSInteger)senceID {
    _senceID = senceID;

    if (senceID == 0) {
        self.brightnessLabel.text = @"0%";
        self.colorTemperatureLabel.text = @"0%";
        self.twinkleLabel.text = @"0s";
        self.senceName = self.senceModel.name;
    } else {
        self.brightnessSlider.value = [self.senceModel.brightness intValue];
        self.colorTemperatureSlider.value = [self.senceModel.colour_temperature intValue];
        self.twinkleSlider.value = [self.senceModel.twinkle intValue];
        self.brightnessLabel.text = [NSString stringWithFormat:@"%@%%",self.senceModel.brightness];
        self.colorTemperatureLabel.text = [NSString stringWithFormat:@"%@%%",self.senceModel.colour_temperature];
        self.twinkleLabel.text = [self getTwinkleWithSliderValue:[self.senceModel.twinkle intValue]];
    }
    
}

@end
